<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\Utils;
use app\admin\model\ProvCityArea;
use app\admin\model\SellGoodsBrandAdress;
use app\admin\model\SellGoodsRefund;

class MachineController extends CommonController {
    /*
     * 售货机列表
     * author xfwed 
     * date 2019.09.19
     */

    public function machineList() {
        $city = input('param.city');
        $searchStr = input('param.search_str');
        $machine_type = input('param.machine_type');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $searchStr = trim($searchStr);
        if ($city) {
            $where['s.city'] = $city;
        }
        $where['m.is_delete'] = 0;
        if (isset($machine_type)) {
            $where['m.machine_type'] = $machine_type;
        } else {
            $where['m.machine_type'] = 1;
        }

        if ($searchStr) {
            $list = Db::table('da_machine_store_relation')->alias('m')
                            ->join('store s', 's.id = m.store_id', 'left')
                            ->where($where)
                            ->where(function ($query) use ($searchStr) {
                                $query->where('s.store_name', 'like', '%' . $searchStr . '%')
                                ->whereOr('m.charge_name', 'like', '%' . $searchStr . '%')
                                ->whereOr('m.charge_tel', 'like', '%' . $searchStr . '%');
                            })
                            ->order('m.id desc')
                            ->field('m.robot_no,m.store_id,m.add_time,m.charge_name,m.charge_tel,m.machine_type,s.store_name,s.city')
                            ->paginate($perPage)->toArray();
        } else {
            $list = Db::table('da_machine_store_relation')->alias('m')
                            ->join('store s', 's.id = m.store_id', 'left')
                            ->where($where)
                            ->order('m.id desc')
                            ->field('m.robot_no,m.store_id,m.add_time,m.charge_name,m.charge_tel,m.machine_type,s.store_name,s.city')
                            ->paginate($perPage)->toArray();
        }

        foreach ($list['data'] as $k => $v) {
            $list['data'][$k]['cityName'] = ProvCityArea::cityName($v['city']);
            $orderdata = Db::table('pay_order')
                    ->where('store_id', '=', $v['store_id'])
                    ->where('status', '>=', 2)
                    ->where('pay_status', '=', 1)
                    ->field('sum(pay_money) as pay_money')
                    ->select();
            $list['data'][$k]['orderNum'] = count($orderdata);
            $list['data'][$k]['payMoney'] = $orderdata[0]['pay_money'];
        }

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 绑定智能设备
     * author xfwed 
     * date 2019.09.20
     */

    public function bindMachine() {
        $rule = [
            'robot_no' => 'require',
            'store_id' => 'require',
            'machine_type' => 'require',
            'charge_name' => 'require',
            'charge_tel' => 'require',
        ];
        $msg = [
            'robot_no.require' => '设备编号必须',
            'store_id.require' => '店铺id必须',
            'machine_type.require' => '类型必须',
            'charge_name.require' => '负责人姓名必须',
            'charge_tel.require' => '负责人手机号必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }

        $robot_no = input('param.robot_no');
        $store_id = input('param.store_id');
        $machine_type = input('param.machine_type');
        $charge_name = input('param.charge_name');
        $charge_tel = input('param.charge_tel');
        $row = Db::table('da_machine_store_relation')
                ->where('store_id', '=', $store_id)
                ->where('machine_type', '=', $machine_type)
                ->where('is_delete', '=', 0)
                ->find();
        if ($row) {
            return $this->ajaxReturn(0, '店铺已经绑定了该种设备', null);
        }
        $robotNoRow = Db::table('da_machine_store_relation')->where('is_delete',0)->where('robot_no', $robot_no)->find();
        if ($robotNoRow) {
            return $this->ajaxReturn(0, '设备号不能重复', null);
        }
        $data = [
            'robot_no' => $robot_no,
            'store_id' => $store_id,
            'add_time' => date('Y-m-d H:i:s'),
            'machine_type' => $machine_type,
            'charge_name' => $charge_name,
            'charge_tel' => $charge_tel,
        ];
        $insertId = Db::table('da_machine_store_relation')->insert($data);
        if ($insertId) {
            return $this->ajaxReturn(0, '绑定成功', null);
        } else {
            return $this->ajaxReturn(3, '绑定失败', null);
        }
    }

    /*
     * 品牌列表
     * author xfwed 
     * date 2019.09.19
     */

    public function brandList() {
        $brandList = Db::table('brand_info')->field('id,name')->select();
        return $this->ajaxReturn(0, '查询成功', $brandList);
    }

    /*
     * 商品分类列表
     * author xfwed 
     * date 2019.09.19
     */

    public function goodsClassList() {
        $goodsClassList = Db::table('goods_category')->field('id,name')->select();
        return $this->ajaxReturn(0, '查询成功', $goodsClassList);
    }

    /*
     * 添加商品
     * author xfwed 
     * date 2019.09.19
     */

    public function addGoods() {
        $rule = [
            'name' => 'require',
            'description' => 'require',
            'icon' => 'require',
//            'white_icon' => 'require',
            'info_img' => 'require',
            'brandId' => 'require',
            'is_import' => 'require',
            'isSelfTake' => 'require',
//            'introduce' => 'require',
            'product_efficacy' => 'require',
            'product_ingredient' => 'require',
            'product_range' => 'require',
            'product_detail' => 'require',
            'skin_type' => 'require',
            'pin_category_type' => 'require',
            'is_dis' => 'require',
            'valid' => 'require',
            'is_smallshopsell' => 'require',
        ];
        $msg = [
            'name.require' => '商品名称标题必须',
            'description.require' => '副标题必须',
            'icon.require' => '主图必须',
//            'white_icon.require' => '白底图必须',
            'info_img.require' => '详情图必须',
            'brandId.require' => '品牌编号必须',
            'is_import.require' => '是否进口必须',
            'isSelfTake.require' => '是否支持自提必须',
//            'introduce.require' => '商品介绍必须',
            'product_efficacy.require' => '产品功效必须',
            'product_ingredient.require' => '产品成分必须',
            'product_range.require' => '产品适用肤质必须',
            'product_detail.require' => '产品明细	必须',
            'skin_type.require' => '肤质类型必须',
            'pin_category_type.require' => '品类类型必须',
            'is_dis.require' => '是否是天天特价产品 1是2否必须',
            'valid.require' => '2保存1上架',
            'is_smallshopsell.require' => '1是2否在小店售卖',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $store_id = isset($store_id) ? $store_id : 0;
        $category_id = $all['category_id']; //商品分类
        $category_id = explode(",", $category_id);

        $goodsImg = $all['goods_img']; //商品图片
        $goodsImg = explode(",", $goodsImg);

        if ($all['is_import'] == 1) {//是否进口,1=是,2=否
            if (empty($all['bgd_img'] || empty($all['wszs_img']))) {
                return $this->ajaxReturn(3, '缺少资质照片', null);
            }
        } else {
            if (empty($all['spzj_img'])) {
                return $this->ajaxReturn(3, '缺少商品质检照片', null);
            }
        }

        Db::startTrans();
        $data = [
            'name' => $all['name'],
            'summary' => $all['description'],
            'icon' => $all['icon'],
//            'white_icon' => $all['white_icon'],
            'brandId' => $all['brandId'],
            'add_time' => date('Y-m-d H:i:s'),
            'is_import' => $all['is_import'],
            'spzj_img' => $all['spzj_img'],
            'bgd_img' => $all['bgd_img'],
            'wszs_img' => $all['wszs_img'],
            'verifyStatus' => 1,
            'isSelfTake' => $all['isSelfTake'],
            'valid' => $all['valid'],
//            'introduce' => $all['introduce'],
            'product_efficacy' => $all['product_efficacy'],
            'product_ingredient' => $all['product_ingredient'],
            'product_range' => $all['product_range'],
            'product_detail' => $all['product_detail'],
            'skin_type' => $all['skin_type'],
            'pin_category_type' => $all['pin_category_type'],
            'is_dis' => $all['is_dis'],
            'is_smallshopsell' => $all['is_smallshopsell'],
            'update_time' => date('Y-m-d H:i:s'),
            'is_bigstar' => $all['is_bigstar'],
            'bigstar_code' => $all['bigstar_code'],
        ];
        $insertId = Db::table('goods_info')->insertGetId($data);
        //生成商品小程序码
        $ApiPath = config('appconfig.ApiPath');
        $postFields['param'] = 'id=' . $insertId . '&d=0&m=0i=0';
        $postFields['url'] = 'packageB/pages/goodsDesc/goodsDesc';
        $relust = Utils::curlPost($ApiPath . '/weChat/getWeChatCodeForUrl/', json_encode($postFields));
        $IndexPath = config('appconfig.IndexPath');
        $relust = json_decode($relust, true)['data'];
        $arr = explode(",", $relust);
        $last = $arr[1];
        $postFields1['img'] = $last;
        $postFields1['modeName'] = 'itemqrcode';
        $relust = Utils::curlPost1($IndexPath . 'Public/uploadBase64Img/', $postFields1);
        $relust = json_decode($relust, true)['data'];
        //生成sku码  	商品sku码 模型代码+分类id（2位）+商品id（6位）
        $code = 'sp';
        $category = sprintf("%02d", $category_id[0]); //补齐二位
        $goodsId = sprintf("%06d", $insertId); //补齐六位
        $goods_sku = $code . $category . $goodsId;

        $saveUniqueId = Db::table('goods_info')
                ->where(['id' => $insertId])
                ->update(['uniqueId' => substr(MD5($insertId), 0, 13), 'xcx_img' => $relust, 'sku' => $goods_sku]);

        $imgData = [];
        foreach ($goodsImg as $key => $value) {
            $oneData = [
                'goods_id' => $insertId,
                'images' => $value,
                'type' => 1,
            ];

            array_push($imgData, $oneData);
        }
        $twoData = [
            'goods_id' => $insertId,
            'images' => $all['info_img'],
            'type' => 2,
        ];
        array_push($imgData, $twoData);
        $imgResult = Db::table('goods_images')->insertAll($imgData);
        $categoryData = [];
        foreach ($category_id as $key => $value) {
            $oneData = [
                'goods_id' => $insertId,
                'category_id' => $value,
            ];

            array_push($categoryData, $oneData);
        }
        $categoryResult = Db::table('goods_info_to_category')->insertAll($categoryData);

        // 商品规格
        Db::table('goods_info_detail')->where('goodsId', '=', $insertId)->delete();
        $detail_arr = [];
//        $arry = [['name'=>'25g*6','oriPrice'=>29800,'isShowOriPrice'=>1,'price'=>8950,'weight'=>150,'start_num'=>1,'stock'=>100,'stock_type'=>1,'valid'=>1,'type'=>1]];
//        print_r(json_encode($arry));die;
        // $all['spec'] = json_decode($all['spec'], TRUE);
        foreach ($all['spec'] as $k => $v) {
            if ($v['price'] < $v['leaveFactoryPrice']) {
                return $this->ajaxReturn(3, '出厂价不能大于现价', null);
            }
            if ($v['price'] < $v['deduct_money']) {
                return $this->ajaxReturn(3, '平台抽成不能大于现价', null);
            }
            if (($v['deduct_money'] + $v['leaveFactoryPrice']) >= $v['price']) {
                return $this->ajaxReturn(3, '出厂价加平台抽成不能大于现价', null);
            }
            $detail_arr[] = [
                'goodsId' => $insertId,
                'name' => $v['name'],
                'oriPrice' => intval($v['oriPrice']),
                'isShowOriPrice' => intval($v['isShowOriPrice']),
                'price' => intval($v['price']),
                'weight' => intval($v['weight']),
                'start_num' => intval($v['start_num']),
                'add_time' => date('Y-m-d H:i:s'),
                'sale_time' => date('Y-m-d H:i:s'),
                'stock' => intval($v['stock']),
                'stock_type' => intval($v['stock_type']),
                'valid' => intval($v['valid']),
                'type' => intval($v['type']),
                'leaveFactoryPrice' => intval($v['leaveFactoryPrice']),
                'deduct_money' => intval($v['deduct_money']),
            ];
        }

        $goosdInfoDetailResult = Db::table('goods_info_detail')->insertAll($detail_arr);

        if ($insertId && $saveUniqueId && $imgResult && $categoryResult && $goosdInfoDetailResult) {
            Db::commit();
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '添加失败', null);
        }
    }

    /*
     * 商品列表
     * author xfwed 
     * date 2019.09.20
     */

    public function goodsList() {
        $valid = input('param.valid');
        $category_id = input('param.category_id');
        $name = input('param.name');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $verifyStatus = input('param.verifyStatus'); //审核状态,1待审核,2成功,3审核拒绝
        $is_dis = input('param.is_dis'); //是否是天天特价产品 0全部1是2否
        $is_xcxsell = input('param.is_xcxsell'); //1是2否在小程序售卖
        $brandId = input('param.brandId'); //品牌id
        $is_index = input('param.is_index'); //1是2否在首页显示
        $is_stick = input('param.is_stick'); //1是2否列表置顶
        $is_smallshopsell = input('param.is_smallshopsell'); //1是2否在小店售卖
        $is_copy = input('param.is_copy'); //1是2否复制到小店了
        $is_bigstar = input('param.is_bigstar'); //1是2否为大牌商品
        $bigstar_code = input('param.bigstar_code'); //大牌商品分类
        $sku = input('param.sku');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        $name = trim($name);

        if ($name) {
            $where['g.name'] = ['like', '%' . $name . '%'];
        }
        if ($valid == 1) {
            $where['g.valid'] = 1;
        } elseif ($valid == 2) {
            $where['g.valid'] = 2;
        } elseif ($valid == 3) {
            $where['g.valid'] = 3;
        }

        if ($category_id) {
            $where['c.category_id'] = $category_id;
        }

        if ($verifyStatus) {
            $where['g.verifyStatus'] = $verifyStatus;
        }

        if ($is_dis) {
            $where['g.is_dis'] = $is_dis;
        }

        if ($is_xcxsell) {
            $where['g.is_xcxsell'] = $is_xcxsell;
        }

        if ($is_index) {
            $where['g.is_index'] = $is_index;
        }

        if ($is_stick) {
            $where['g.is_stick'] = $is_stick;
        }

        if ($brandId) {
            $where['g.brandId'] = $brandId;
        }

        if ($is_smallshopsell) {
            $where['g.is_smallshopsell'] = $is_smallshopsell;
        }

        if ($is_copy) {
            $where['g.is_copy'] = $is_copy;
            $where['g.is_smallshopsell'] = 2;
        }

        if ($is_bigstar) {
            $where['g.is_bigstar'] = $is_bigstar;
        }

        if ($bigstar_code) {
            $where['g.bigstar_code'] = $bigstar_code;
        }

        if ($sku) {
            $where['g.sku'] = $sku;
        }
        $where = isset($where) ? $where : [];

        $goodsList = Db::table('goods_info')->alias('g')
                ->join(['goods_info_to_category' => 'c'], 'g.id=c.goods_id', 'left')
                ->join(['goods_info_detail' => 'd'], 'd.goodsId = g.id', 'left')
                ->where($where)
                ->field('g.id,g.name,g.icon,g.is_dis,g.is_xcxsell,g.is_index,g.is_stick,d.oriPrice,d.price,g.add_time,g.valid,d.stock,g.is_smallshopsell,g.is_copy,g.is_bigstar,g.bigstar_code,g.verifyStatus,g.sell_count,g.virtual_sell_count,g.sku')
                ->order('sort desc,id desc')
                ->group('g.id')
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $goodsList);
    }

    /*
     * 商品上架/下架
     * author xfwed 
     * date 2019.09.20
     */

    public function upperGoods() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
            'valid' => 'require|integer',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
            'valid.require' => '请选择上架或者下架',
            'valid.integer' => '上架或者下架编号为数字',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $data = [
            'valid' => $post['valid'],
            'update_time' => date('Y-m-d H:i:s'),
        ];

        Db::table('goods_info')->where('id', 'in', $post['goodsId'])->update($data);
        if ($post['valid'] == 1) {
            $msg = '上架成功';
        } else {
            $msg = '下架成功';
        }
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $post['goodsId']);
        return $this->ajaxReturn(0, $msg, null);
    }

    /*
     * 商品订单列表
     * author xfwed 
     * date 2019.09.20
     */

    public function goodsOrderList() {
        $status = input('param.status');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $ord_num = input('ord_num');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $is_minishop = input('param.is_minishop'); //1是2否 小店订单
        $goodsname = input('param.goodsname');
        $is_big_brand = input('param.is_big_brand'); //1是2否 大牌商品订单
        $name = input('param.name'); //收货人姓名
        $phone = input('param.phone'); //收货人手机号
        $custom_phone = input('param.custom_phone'); //用户手机号
        $pay_status = input('param.pay_status'); //0全部 1已支付 2未支付
        $store_type = input('param.store_type'); //店铺类型 0全部 1品牌连锁店 2服务授权店

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($status && ($status != 5 && $status != 6)) {
            $where['pd.status'] = $status;
            $where['pg.is_refund'] = ['in', '0,3'];
        }
        if ($status == -1) {
            $where['pd.status'] = 0;
            $where['pg.is_refund'] = ['in', '0,3'];
        }

        if ($status == 5) {
            $where['pg.is_refund'] = 1;
        }

        if ($status == 6) {
            $where['pg.is_refund'] = 2;
        }

        if ($ord_num) {
            $where['pd.order_id'] = $ord_num;
        }
        if ($is_minishop == 1) {
            $where['pd.mini_shop_id'] = ['<>', 0];
        } elseif ($is_minishop == 2) {
            $where['pd.mini_shop_id'] = 0;
        }

        if ($goodsname) {
            $where['pg.name'] = ['like', '%' . $goodsname . '%'];
        }

        if ($is_big_brand == 1) {
            $where['pd.activity_big_brand_id'] = ['<>', 0];
        } elseif ($is_big_brand == 2) {
            $where['pd.activity_big_brand_id'] = 0;
        }

        if ($end_time && $start_time) {
            $where['pd.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['pd.add_time'] = array('between', array($time, $time2));
        }

        if ($name) {
            $where['pd.name'] = ['like', '%' . $name . '%'];
        }
        if ($phone) {
            $where['pd.phone'] = $phone;
        }
        if ($custom_phone) {
            $where['c.custom_phone'] = $custom_phone;
        }
        if ($pay_status) {//0全部 1已支付 2未支付
            if ($pay_status == 1) {
                $where['pd.pay_status'] = ['in', '1,2,3'];
            } elseif ($pay_status == 2) {
                $where['pd.pay_status'] = ['in', '0,4'];
            }
        }
        if ($store_type) {
            $where['s.type'] = $store_type;
        }
        //$where['m.machine_type'] = 1;
        $where = isset($where) ? $where : [];
        $goodsOrderList = Db::table('pay_order_detail')->alias('pd')
                        ->join(['pay_order_goods' => 'pg'], 'pg.pay_order_id = pd.id', 'left')
                        ->join('store s', 's.id = pd.store_id', 'left')
                        ->join('custom c', 'c.id=pd.ctm_id', 'left')
                        ->join(['brand_info' => 'b'], 'b.id = pd.brand_id', 'left')
                        //->join(['da_machine_store_relation' => 'm'], 'm.store_id = pd.store_id','right')
                        ->where($where)
                        ->field('pd.id,pd.order_id,pd.mini_shop_id,pd.activity_big_brand_id,pg.name,pg.goods_icon,pg.is_refund,s.store_name,s.type store_type,pd.add_time create_time,c.custom_name,c.custom_phone,pd.pay_money,pd.status,b.name brand_name')
                        ->group('pd.id')
                        ->order('pd.id desc')
                        ->paginate($perPage)->toArray();
//        print_r(Db::table('pay_order')->getLastSql());
//        print_r($goodsOrderList->toArray());
        foreach ($goodsOrderList['data'] as $k => $v) {
            $pgISRefund = $v['is_refund'];
            if ($pgISRefund == 1) {
                $goodsOrderList['data'][$k]['status'] = 5; //已发起退款
            }
            if ($pgISRefund == 2) {
                $goodsOrderList['data'][$k]['status'] = 6; //已退款
            }
            $tel = Db::connect('mysql://root:eDKmpHzrfkcKrHavT5NLuQ@47.104.18.180:3306/mbcnew#utf8')
                    ->table('brand_info')->alias('b')
                    ->join(['company_info' => 'c'], 'b.companyId = c.id', 'left')
                    ->where('b.name', $v['brand_name'])
                    ->value('c.tel');
            $goodsOrderList['data'][$k]['tel'] = $tel;
            //判断大牌商品的状态
            $status = $v['status'];
            $activity_big_brand_id = $v['activity_big_brand_id'];
            $order_detail_id = $v['id'];
            if ($status == 1 && $activity_big_brand_id != 0) {
                $advanceRow = Db::table('goods_advance')
                        ->where('order_detail_id', $order_detail_id)
                        ->order('id desc')
                        ->find();
                $type = $advanceRow['type'];
                $status = $advanceRow['status'];
                if ($type == 1) {
                    if ($status != 1) {//没有付定金
                        $goodsOrderList['data'][$k]['status'] = 11; //11待付定金 12等待成团 13待付尾款
                    } else {//付定金了  判断成团没有
                        $groupStatus = Db::table('goods_group_detail')->alias('ggd')
                                ->join([' goods_group' => 'gg'], 'ggd.group_id = gg.id', 'left')
                                ->where('ggd.order_detail_id', $order_detail_id)
                                ->value('gg.status');
                        if ($groupStatus == 1) {
                            $goodsOrderList['data'][$k]['status'] = 12;
                        } else {
                            $goodsOrderList['data'][$k]['status'] = 13;
                        }
                    }
                } elseif ($type == 2) {
                    if ($status != 1) {
                        $goodsOrderList['data'][$k]['status'] = 13;
                    }
                }
            }
        }
        //$goodsOrderList->toArray()['data'] = $data;

        return $this->ajaxReturn(0, '查询成功', $goodsOrderList);
    }

    /*
     * 商品订单详情
     * author xfwed 
     * date 2019.09.20
     */

    public function goodsOrderInfo() {
        $id = input('param.id');

        $detail = Db::table('pay_order_detail')->alias('o')
                ->join('custom c', 'c.id = o.ctm_id', 'left')
                ->where('o.id', '=', $id)
                ->field('o.id,o.order_id,o.pay_money,o.pay_num,o.add_time,o.pay_time,o.name,o.phone,o.province_id,o.city_id,o.area_id,o.address,o.logistics_num,o.status,o.activity_big_brand_id,c.custom_name,c.custom_phone')
                ->find();

        $goodsinfo = Db::table('pay_order_goods')
                ->where('pay_order_id', '=', $detail['id'])
                ->field('id,name,goods_icon,price,goods_detail_name,number')
                ->select();
        $detail['goodsinfo'] = $goodsinfo;
        $provinceName = ProvCityArea::where('id', $detail['province_id'])->value('name');
        $cityName = ProvCityArea::where('id', $detail['city_id'])->value('name');
        $areaName = ProvCityArea::where('id', $detail['area_id'])->value('name');
        $detail['address'] = $provinceName . $cityName . $areaName . $detail['address'];
        //判断大牌商品的状态
        $status = $detail['status'];
        $activity_big_brand_id = $detail['activity_big_brand_id'];
        $order_detail_id = $detail['id'];
        if ($status == 1 && $activity_big_brand_id != 0) {
            $advanceRow = Db::table('goods_advance')
                    ->where('order_detail_id', $order_detail_id)
                    ->order('id desc')
                    ->find();
            $type = $advanceRow['type'];
            $status = $advanceRow['status'];
            if ($type == 1) {
                if ($status != 1) {//没有付定金
                    $detail['status'] = 11; //11待付定金 12等待成团 13待付尾款
                } else {//付定金了  判断成团没有
                    $groupStatus = Db::table('goods_group_detail')->alias('ggd')
                            ->join(['goods_group' => 'gg'], 'ggd.group_id = gg.id', 'left')
                            ->where('ggd.order_detail_id', $order_detail_id)
                            ->value('gg.status');
                    if ($groupStatus == 1) {
                        $detail['status'] = 12;
                    } else {
                        $detail['status'] = 13;
                    }
                }
            } elseif ($type == 2) {
                if ($status != 1) {
                    $detail['status'] = 13;
                }
            }
        }
        //查询大牌商品的支付订单
        $advanceList = Db::table('goods_advance')
                ->where('order_detail_id', $order_detail_id)
                ->field('id,type,pay_money,balance_money,ord_num,status,add_time,pay_time')
                ->order('id asc')
                ->select();
        $detail['advanceList'] = $advanceList;
        //查询大牌商品的拼团信息
        $group_id = Db::table('goods_group_detail')->where('order_detail_id', $order_detail_id)->value('group_id');
        $groupList = Db::table('goods_group_detail')->alias('ggd')
                ->join('custom c', 'c.id = ggd.ctm_id', 'left')
                ->where('ggd.group_id', $group_id)
                ->field('ggd.id,ggd.add_time,ggd.status,c.custom_phone,c.custom_name,c.custom_photo')
                ->select();
        $groupRow = Db::table('goods_group')
                ->where('id', $group_id)
                ->field('num,all_num,status,add_time')
                ->find();
        $groupRow['list'] = $groupList;
        $detail['groupInfo'] = $groupRow;

        return $this->ajaxReturn(0, '查询成功', $detail);
    }

    /*
     * 添加售后地址
     * author xfwed 
     * date 2019.12.06
     */

    public function addAfterSaleAddress() {
        $rule = [
            'brand_id' => 'require',
            'brand_address' => 'require',
            'brand_name' => 'require',
            'brand_tel' => 'require',
        ];
        $msg = [
            'brand_id.require' => '品牌id必须',
            'brand_address.require' => '收货地址必须',
            'brand_name.require' => '联系姓名必须',
            'brand_tel.require' => '联系电话必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $brand_id = $all['brand_id'];
        $brand_address = $all['brand_address'];
        $brand_name = $all['brand_name'];
        $brand_tel = $all['brand_tel'];
        $row = SellGoodsBrandAdress::where('brand_id', $brand_id)->where('is_del', 0)->find();
        if ($row) {
            $save = SellGoodsBrandAdress::where('brand_id', $brand_id)
                    ->where('is_del', 0)
                    ->update([
                'brand_address' => $brand_address,
                'brand_name' => $brand_name,
                'brand_tel' => $brand_tel,
                'add_time' => date('Y-m-d H:i:s', time()),
            ]);
        } else {
            $insert = SellGoodsBrandAdress::insert([
                        'brand_id' => $brand_id,
                        'brand_address' => $brand_address,
                        'brand_name' => $brand_name,
                        'brand_tel' => $brand_tel,
                        'add_time' => date('Y-m-d H:i:s', time()),
            ]);
        }

        return $this->ajaxReturn(0, '添加成功', null);
    }

    /*
     * 删除售后地址
     * author xfwed 
     * date 2019.12.06
     */

    public function delAfterSaleAddress() {
        $rule = [
            'id' => 'require',
        ];
        $msg = [
            'id.require' => 'id必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            return $this->ajaxReturn(1, $error, null);
        }
        $id = $all['id'];
        $row = SellGoodsBrandAdress::where('id', $id)->update(['is_del' => 1]);
        return $this->ajaxReturn(0, '删除成功', null);
    }

    /*
     * 售后地址列表
     * author xfwed 
     * date 2019.12.06
     */

    public function afterSaleAddressList() {
        $brand_id = input('brand_id');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;

        if ($brand_id) {
            $where['s.brand_id'] = $brand_id;
        }
        $where['is_del'] = 0;
        $list = SellGoodsBrandAdress::alias('s')
                ->join(['brand_info' => 'b'], 'b.id = s.brand_id', 'left')
                ->where($where)
                ->field('s.*,b.name')
                ->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 商品详情
     * author xfwed
     * date 2019.12.09
     */

    public function goodsInfo() {
        $id = input('param.id');
        $goodsInfo = Db::table('goods_info')
                ->field('id,name,summary,icon,brandId,is_import,spzj_img,bgd_img,wszs_img,isSelfTake,product_efficacy,product_ingredient,product_range,product_detail,skin_type,pin_category_type,is_dis,is,bigstar')
                ->where('id', $id)
                ->find();
        $data['goodsInfo'] = $goodsInfo;
        //商品规格// goods_info_detail"产品规格表"
        $goodsInfoDetail = Db::table('goods_info_detail')
                ->where('goodsId', $id)
                ->select();
        $data['goodsInfoDetail'] = $goodsInfoDetail;
        //商品分类goods_info_to_category"商品对应分类关系表"
        $goodsInfoToCategory = Db::table('goods_info_to_category')->alias('g')
                ->join(['goods_category' => 'c'], 'c.id=g.category_id', 'left')
                ->field('c.id,c.name')
                ->where('goods_id', $id)
                ->select();
        $data['goodsInfoToCategory'] = $goodsInfoToCategory;
        //商品图片goods_images"产品图片表"
        $goodsImages = Db::table('goods_images')
                ->field('images,type')
                ->where('goods_id', $id)
                ->select();
        $data['goodsImages'] = $goodsImages;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 商品审核
     * author xfwed 
     * date 2019.12.09
     */

    public function auditGoods() {
        $id = input('param.id');
        $status = input('param.verifyStatus');
        $why = input('param.why');

        if ($status == 3 && empty($why)) {
            return $this->ajaxReturn(3, '请填写拒绝原因', null);
        }
        if ($status == 2) {
            $valid = 1;
            $why = NULL;
        } elseif ($status == 3) {
            $valid = 2;
        }
        $save = Db::table('goods_info')->where('id', $id)->update([
            'verifyStatus' => $status,
            'why' => $why,
            'valid' => $valid,
            'update_time' => date('Y-m-d H:i:s'),
        ]);
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $id);
        if ($save) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }

    /*
     * 修改商品
     * author xfwed 
     * date 2019.09.19
     */

    public function saveGoods() {
        $requestType = input('param.requestType');
        $id = input('param.id');
        if ($requestType == 1) {//1修改前获取信息 2提交修改
            $goodsInfo = Db::table('goods_info')
                    //->field('id,name,summary,icon,brandId,is_import,spzj_img,bgd_img,wszs_img,isSelfTake,product_efficacy,product_ingredient,product_range,product_detail,skin_type,pin_category_type,is_dis')
                    ->where('id', $id)
                    ->find();
            //商品规格// goods_info_detail"产品规格表"
            $goodsInfoDetail = Db::table('goods_info_detail')
                    ->where('goodsId', $id)
                    ->select();
            $goodsInfo['spec'] = $goodsInfoDetail;
            //商品分类goods_info_to_category"商品对应分类关系表"
            $goodsInfoToCategory = Db::table('goods_info_to_category')
                    ->where('goods_id', $id)
                    ->select();
            $goodsInfo['category_id'] = $goodsInfoToCategory[0]['category_id'];
            //商品图片goods_images"产品图片表"
            $goodsImages = Db::table('goods_images')
                    ->field('images url')
                    ->where('goods_id', $id)
                    ->where('type', 1)
                    ->select();
            $goodsInfo['goods_img'] = $goodsImages;
            $goodsInfo['info_img'] = Db::table('goods_images')
                    ->where('goods_id', $id)
                    ->where('type', 2)
                    ->value('images');
            return $this->ajaxReturn(0, '查询成功', $goodsInfo);
        } else {
            $rule = [
                'name' => 'require',
                'description' => 'require',
                'icon' => 'require',
//            'white_icon' => 'require',
//                'info_img' => 'require',
                'brandId' => 'require',
                'is_import' => 'require',
                'isSelfTake' => 'require',
//            'introduce' => 'require',
                'product_efficacy' => 'require',
                'product_ingredient' => 'require',
                'product_range' => 'require',
                'product_detail' => 'require',
                'skin_type' => 'require',
                'pin_category_type' => 'require',
                'is_dis' => 'require',
                'valid' => 'require',
                'is_smallshopsell' => 'require',
            ];
            $msg = [
                'name.require' => '商品名称标题必须',
                'description.require' => '副标题必须',
                'icon.require' => '主图必须',
//            'white_icon.require' => '白底图必须',
//                'info_img.require' => '详情图必须',
                'brandId.require' => '品牌编号必须',
                'is_import.require' => '是否进口必须',
                'isSelfTake.require' => '是否支持自提必须',
//            'introduce.require' => '商品介绍必须',
                'product_efficacy.require' => '产品功效必须',
                'product_ingredient.require' => '产品成分必须',
                'product_range.require' => '产品适用肤质必须',
                'product_detail.require' => '产品明细	必须',
                'skin_type.require' => '肤质类型必须',
                'pin_category_type.require' => '品类类型必须',
                'is_dis.require' => '是否是天天特价产品 1是2否必须',
                'valid.require' => '2仓库1上架',
                'is_smallshopsell.require' => '1是2否在小店售卖',
            ];
            $all = input('param.');
            $validate = new Validate($rule, $msg);

            if (!$validate->check($all)) {
                $error = $validate->getError();
                return $this->ajaxReturn(1, $error, null);
            }
            $store_id = isset($store_id) ? $store_id : 0;
            $category_id = $all['category_id']; //商品分类
            $category_id = explode(",", $category_id);

            $goodsImg = $all['goods_img']; //商品图片
            $goodsImg = explode(",", $goodsImg);

            if ($all['is_import'] == 1) {//是否进口,1=是,2=否
                if (empty($all['bgd_img'] || empty($all['wszs_img']))) {
                    return $this->ajaxReturn(3, '缺少资质照片', null);
                }
            } else {
                if (empty($all['spzj_img'])) {
                    return $this->ajaxReturn(3, '缺少商品质检照片', null);
                }
            }

            Db::startTrans();
            //生成sku码  	商品sku码 模型代码+分类id（2位）+商品id（6位）
            $code = 'sp';
            $category = sprintf("%02d", $category_id[0]); //补齐二位
            $goodsId = sprintf("%06d", $id); //补齐六位
            $goods_sku = $code . $category . $goodsId;
            $data = [
                'name' => $all['name'],
                'summary' => $all['description'],
                'icon' => $all['icon'],
//            'white_icon' => $all['white_icon'],
                'brandId' => $all['brandId'],
//                'add_time' => date('Y-m-d H:i:s'),
                'is_import' => $all['is_import'],
                'spzj_img' => $all['spzj_img'],
                'bgd_img' => $all['bgd_img'],
                'wszs_img' => $all['wszs_img'],
                'verifyStatus' => 1,
                'isSelfTake' => $all['isSelfTake'],
                'valid' => $all['valid'],
//            'introduce' => $all['introduce'],
                'product_efficacy' => $all['product_efficacy'],
                'product_ingredient' => $all['product_ingredient'],
                'product_range' => $all['product_range'],
                'product_detail' => $all['product_detail'],
                'skin_type' => $all['skin_type'],
                'pin_category_type' => $all['pin_category_type'],
                'is_dis' => $all['is_dis'],
                'is_smallshopsell' => $all['is_smallshopsell'],
                'update_time' => date('Y-m-d H:i:s'),
                'is_bigstar' => $all['is_bigstar'],
                'bigstar_code' => $all['bigstar_code'],
                'sku' => $goods_sku,
            ];
            $insertId = Db::table('goods_info')->where('id', $id)->update($data);

            $imgData = [];
            foreach ($goodsImg as $key => $value) {
                $oneData = [
                    'goods_id' => $id,
                    'images' => $value,
                    'type' => 1,
                ];

                array_push($imgData, $oneData);
            }
            $twoData = [
                'goods_id' => $id,
                'images' => $all['info_img'],
                'type' => 2,
            ];
            array_push($imgData, $twoData);
            $delResult = Db::table('goods_images')->where('goods_id', '=', $id)->delete();
            $imgResult = Db::table('goods_images')->insertAll($imgData);
            $categoryData = [];
            foreach ($category_id as $key => $value) {
                $oneData = [
                    'goods_id' => $id,
                    'category_id' => $value,
                ];

                array_push($categoryData, $oneData);
            }
            $delcategoryResult = Db::table('goods_info_to_category')->where('goods_id', '=', $id)->delete();
            $categoryResult = Db::table('goods_info_to_category')->insertAll($categoryData);

            // 商品规格
            Db::table('goods_info_detail')->where('goodsId', '=', $id)->delete();
            $detail_arr = [];
//        $arry = [['name'=>'25g*6','oriPrice'=>29800,'isShowOriPrice'=>1,'price'=>8950,'weight'=>150,'start_num'=>1,'stock'=>100,'stock_type'=>1,'valid'=>1,'type'=>1]];
//        print_r(json_encode($arry));die;
//             $all['spec'] = json_decode($all['spec'], TRUE);
            foreach ($all['spec'] as $k => $v) {
                if ($v['price'] < $v['leaveFactoryPrice']) {
                    return $this->ajaxReturn(3, '出厂价不能大于现价', null);
                }
                if ($v['price'] < $v['deduct_money']) {
                    return $this->ajaxReturn(3, '平台抽成不能大于现价', null);
                }
                if (($v['deduct_money'] + $v['leaveFactoryPrice']) >= $v['price']) {
                    return $this->ajaxReturn(3, '出厂价加平台抽成不能大于现价', null);
                }
                $detail_arr[] = [
                    'goodsId' => $id,
                    'name' => $v['name'],
                    'oriPrice' => intval($v['oriPrice']),
                    'isShowOriPrice' => intval($v['isShowOriPrice']),
                    'price' => intval($v['price']),
                    'weight' => intval($v['weight']),
                    'start_num' => intval($v['start_num']),
                    'add_time' => date('Y-m-d H:i:s'),
                    'sale_time' => date('Y-m-d H:i:s'),
                    'stock' => intval($v['stock']),
                    'stock_type' => intval($v['stock_type']),
                    'valid' => intval($v['valid']),
                    'type' => intval($v['type']),
                    'leaveFactoryPrice' => intval($v['leaveFactoryPrice']),
                    'deduct_money' => intval($v['deduct_money']),
                ];
            }

            $goosdInfoDetailResult = Db::table('goods_info_detail')->insertAll($detail_arr);

            if ($insertId && $imgResult && $categoryResult && $goosdInfoDetailResult) {
                Db::commit();
                $ApiPath = config('appconfig.ApiPath');
                $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $id);
                return $this->ajaxReturn(0, '修改成功', null);
            } else {
                Db::rollback();
                return $this->ajaxReturn(3, '修改失败', null);
            }
        }
    }

    /*
     * 商品售后列表
     * author xfwed 
     * date 2019.12.16
     */

    public function goodsRefundList() {
        $is_refund = input('param.is_refund'); //退款状态  0否1是2退款成功3退款失败
        $ord_num = input('param.ord_num');
        $perPage = input('param.perPage');
        $page = input('param.page');
        $vip_status = input('param.vip_status'); //用户级别
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $is_minishop = input('param.is_minishop'); //1是2否 小店订单

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($is_refund) {
            $where['o.is_refund'] = $is_refund;
        } else {
            $where['o.is_refund'] = ['in', '1,2,3'];
        }
        if ($ord_num) {
            $where['d.order_id'] = $ord_num;
        }
        if ($vip_status) {
            $where['c.vip_status'] = $vip_status;
        }
        if ($is_minishop == 1) {
            $where['d.mini_shop_id'] = ['<>', 0];
        } elseif ($is_minishop == 2) {
            $where['d.mini_shop_id'] = 0;
        }

        if ($end_time && $start_time) {
            $where['s.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['s.add_time'] = array('between', array($time, $time2));
        }
        $where['s.status'] = 1;
        $list = Db::table('pay_order_goods')->alias('o')
                ->join(['pay_order_detail' => 'd'], 'd.id = o.pay_order_id', 'left')
                ->join(['brand_info' => 'b'], 'b.id = d.brand_id', 'left')
                ->join('custom c', 'c.id = d.ctm_id', 'left')
                ->join('sell_goods_refund s', 's.pay_orders_goods_id = o.id', 'left')
                ->where($where)
                ->field('o.id,o.name,o.price,o.number,o.is_refund,d.order_id,d.mini_shop_id,b.name brand_name,c.custom_name,s.add_time')
                ->paginate($perPage);

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 商品售后详情
     * author xfwed 
     * date 2019.12.17
     */

    public function goodsRefundInfo() {
        $id = input('param.id'); //订单id
        $where['o.id'] = $id;
        //申请信息
        $data['applyInfo'] = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 1)->find();
        $data['applyInfo']['certificate_photo'] = substr($data['applyInfo']['certificate_photo'], 0, -1);
        $data['applyInfo']['certificate_photo'] = explode(",", $data['applyInfo']['certificate_photo']);
        $orderRow = Db::table('pay_order_goods')->alias('o')
                ->join(['pay_order_detail' => 'd'], 'd.id = o.pay_order_id', 'left')
                ->join(['brand_info' => 'b'], 'b.id = d.brand_id', 'left')
                ->join('custom c', 'c.id = d.ctm_id', 'left')
//                ->join('sell_goods_refund s','s.pay_orders_goods_id = o.id','left')
                ->where($where)
                ->field('o.id,o.goods_id,o.name,o.price,o.number,o.is_refund,d.order_id,b.name brand_name,c.custom_name,c.custom_phone,d.province_id,d.city_id,d.area_id,d.address,d.pay_time,d.add_time')
                ->find();
        $province_name = ProvCityArea::where('id', $orderRow['province_id'])->value('name');
        $city_name = ProvCityArea::where('id', $orderRow['city_id'])->value('name');
        $area_name = ProvCityArea::where('id', $orderRow['area_id'])->value('name');
        $orderRow['address'] = $province_name . $city_name . $area_name . $orderRow['address'];
        unset($orderRow['province_id']);
        unset($orderRow['city_id']);
        unset($orderRow['area_id']);
        $data['orderRow'] = $orderRow;
        //商品信息
        $data['goodsInfo'] = Db::table('goods_info')->where('id', $orderRow['goods_id'])
                ->field('id,name,icon')
                ->find();
        $data['goodsInfo']['price'] = $orderRow['price'];
        $data['goodsInfo']['number'] = $orderRow['number'];
        //平台审核信息
        $ptAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 2)->field('status,audit_name,add_time,refuse_reason')->find();
        if (empty($ptAuditInfo)) {
            $ptAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 9)->field('status,audit_name,add_time,refuse_reason')->find();
        }
        $data['ptAuditInfo'] = $ptAuditInfo;
        //厂商审核信息
        $csAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 6)->field('status,audit_name,add_time,refuse_reason')->find();
        if (empty($csAuditInfo) && !empty($ptAuditInfo) && $ptAuditInfo['status'] != 9) {
            $csAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 9)->field('status,audit_name,add_time,refuse_reason')->find();
        }
        $data['csAuditInfo'] = $csAuditInfo;
        //财务审核信息
        $cwAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 7)->field('status,audit_name,add_time,refuse_reason')->find();
        if (empty($cwAuditInfo) && !empty($csAuditInfo) && $csAuditInfo['status'] != 9) {
            $cwAuditInfo = SellGoodsRefund::where('pay_orders_goods_id', $id)->where('status', 9)->field('status,audit_name,add_time,refuse_reason')->find();
        }
        $data['cwAuditInfo'] = $cwAuditInfo;
        return $this->ajaxReturn(0, '查询成功', $data);
    }

    /*
     * 商品退款第一步审核
     * author xfwed
     * date 2019-12-17
     */

    public function oneAuditGoodsRefund() {
        $id = input('param.id');
        $status = input('param.status'); //2成功9拒绝
        $refuse_reason = input('param.refuse_reason'); //失败的原因
        $audit_name = input('param.audit_name');
        if ($status == 9 && empty($refuse_reason)) {
            return $this->ajaxReturn(3, '请输入拒绝原因', null);
        }
        if ($status != 2 && $status != 9) {
            return $this->ajaxReturn(3, '状态错误', null);
        }
        $row = SellGoodsRefund::where('pay_orders_goods_id', $id)->order('status desc')->find();
        if ($row['status'] != 1) {
            return $this->ajaxReturn(3, '平台已经审核过了', null);
        }
        $data['pay_orders_goods_id'] = $id;
        $data['apply_reason'] = $row['apply_reason'];
        $data['refund_note'] = $row['refund_note'];
        $data['certificate_photo'] = $row['certificate_photo'];
        $data['status'] = $status;
        $data['refuse_reason'] = $refuse_reason;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['service_no'] = $row['service_no'];
        $data['audit_name'] = $audit_name;
        $insert = SellGoodsRefund::insert($data);
        if ($status == 9) {
            $result = Db::table('pay_order_goods')->where('id', $id)->update(['is_refund' => 3]);
        } else {
            $result = TRUE;
        }
        if ($insert && $result) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }

    /*
     * 商品退款第二步审核
     * author xfwed
     * date 2019-12-17
     */

    public function twoAuditGoodsRefund() {
        $id = input('param.id');
        $status = input('param.status'); //7成功9拒绝
        $refuse_reason = input('param.refuse_reason'); //失败的原因
        $audit_name = input('param.audit_name');
        if ($status == 9 && empty($refuse_reason)) {
            return $this->ajaxReturn(3, '请输入拒绝原因', null);
        }
        if ($status != 7 && $status != 9) {
            return $this->ajaxReturn(3, '状态错误', null);
        }
        $row = SellGoodsRefund::where('pay_orders_goods_id', $id)->order('status desc')->find();
        if ($row['status'] > 6) {
            return $this->ajaxReturn(3, '平台财务已经审核过了', null);
        }
        if ($row['status'] < 6) {
            return $this->ajaxReturn(3, '需等待厂商审核通过后方可审核', null);
        }
        $data['pay_orders_goods_id'] = $id;
        $data['apply_reason'] = $row['apply_reason'];
        $data['refund_note'] = $row['refund_note'];
        $data['certificate_photo'] = $row['certificate_photo'];
        $data['status'] = $status;
        $data['refuse_reason'] = $refuse_reason;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['service_no'] = $row['service_no'];
        $data['audit_name'] = $audit_name;
        $insert = SellGoodsRefund::insert($data);
        if ($status == 7) {
            $ApiPath = config('appconfig.ApiPath');
            $result = Utils::curlPost1($ApiPath . 'thirdPay/sellGoodsRefund/' . $id);
            $result = json_decode($result, TRUE);
            if ($result['code'] == 0) {
                $result = TRUE;
            } else {
                $result = FALSE;
            }
        } elseif ($status == 9) {
            $result = Db::table('pay_order_goods')->where('id', $id)->update(['is_refund' => 3]);
        }
        if ($insert && $result) {
            return $this->ajaxReturn(0, '审核成功', null);
        } else {
            return $this->ajaxReturn(3, '审核失败', null);
        }
    }

    /*
     * 设置/取消天天特价
     * author xfwed 
     * date 2020.01.13
     */

    public function upperGoodsDis() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
            'is_dis' => 'require|integer',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
            'is_dis.require' => '请选择设置或者取消',
            'is_dis.integer' => '设置或者取消编号为数字',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $data = [
            'is_dis' => $post['is_dis']
        ];

        Db::table('goods_info')->where('id', '=', $post['goodsId'])->update($data);
        if ($post['is_dis'] == 1) {
            $msg = '设置成功';
        } else {
            $msg = '取消成功';
        }
        return $this->ajaxReturn(0, $msg, null);
    }

    /*
     * 小程序商品上架/下架
     * author xfwed 
     * date 2020.02.26
     */

    public function upperXcxGoods() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
            'valid' => 'require|integer',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
            'valid.require' => '请选择上架或者下架',
            'valid.integer' => '上架或者下架编号为数字',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $data = [
            'is_xcxsell' => $post['valid']
        ];

        Db::table('goods_info')->where('id', 'in', $post['goodsId'])->update($data);
        if ($post['valid'] == 1) {
            $msg = '上架成功';
        } else {
            $msg = '下架成功';
        }
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $post['goodsId']);
        return $this->ajaxReturn(0, $msg, null);
    }

    /*
     * 修改商品规格
     * author xfwed 
     * date 2020.03.20
     */

    public function saveGoodsInfoDetail() {
        $id = input('param.id');
        $all = input('param.');
        if ($all['price'] < $all['leaveFactoryPrice']) {
            return $this->ajaxReturn(3, '出厂价不能大于现价', null);
        }
        if ($all['price'] < $all['deduct_money']) {
            return $this->ajaxReturn(3, '平台抽成不能大于现价', null);
        }
        if (($all['deduct_money'] + $all['leaveFactoryPrice']) >= $all['price']) {
            return $this->ajaxReturn(3, '出厂价加平台抽成不能大于现价', null);
        }
        // 商品规格
        $detail_arr = [
            //'goodsId' => $id,
            'name' => $all['name'],
            'oriPrice' => intval($all['oriPrice']),
            'isShowOriPrice' => intval($all['isShowOriPrice']),
            'price' => intval($all['price']),
            'weight' => intval($all['weight']),
            'start_num' => intval($all['start_num']),
            //'add_time' => date('Y-m-d H:i:s'),
            'sale_time' => date('Y-m-d H:i:s'),
            'stock' => intval($all['stock']),
            'stock_type' => intval($all['stock_type']),
            'valid' => intval($all['valid']),
            'type' => intval($all['type']),
            'leaveFactoryPrice' => intval($all['leaveFactoryPrice']),
            'deduct_money' => intval($all['deduct_money']),
        ];

        $goosdInfoDetail = Db::table('goods_info_detail')
                ->where('id', $id)
                ->find();
        if (empty($goosdInfoDetail)) {
            return $this->ajaxReturn(3, 'id有误', null);
        }
        $goosdInfoDetailResult = Db::table('goods_info_detail')
                ->where('id', $id)
                ->update($detail_arr);
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $goosdInfoDetail['goodsId']);
        if ($goosdInfoDetailResult) {
            return $this->ajaxReturn(0, '修改成功', null);
        } else {
            return $this->ajaxReturn(3, '修改失败', null);
        }
    }

    /*
     * 商品排序
     * 首页置顶 和 参加逆行者活动的产品
     * author xfwed 
     * date 2020.04.30
     */

    public function sortGoods() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
            'type' => 'require',
            'valid' => 'require|integer',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
            'type.require' => '分类必须',
            'valid.require' => '请选择上架或者下架',
            'valid.integer' => '上架或者下架编号为数字',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $goodsId = $post['goodsId'];
        $type = $post['type']; //1首页显示  2列表置顶（参加逆行者的产品）
        $valid = $post['valid'];

        if ($type == 1) {
            $data = [
                'is_index' => $valid
            ];
        } elseif ($type == 2) {
            $data = [
                'is_stick' => $valid
            ];
        }
        $row = Db::table('goods_info')->where('id', 'in', $goodsId)->update($data);
        if ($row) {
            return $this->ajaxReturn(0, '操作成功', null);
        } else {
            return $this->ajaxReturn(3, '操作失败', null);
        }
    }

    /*
     * 复制商品到小店
     * author xfwed 
     * date 2020.05.07
     */

    public function copyGoods() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $goodsId = $post['goodsId'];

        $row = Db::table('goods_info')->where('id', 'in', $goodsId)
                ->field('id,sell_count,visit_count,uniqueId,is_dis,is_xcxsell,is_index,is_stick,verifyStatus', true)
                ->find(); //update_time  add_time  uniqueId  is_smallshopsell
        if ($row['is_copy'] == 1) {
            return $this->ajaxReturn(3, '您已经复制过该商品了', null);
        }
        Db::startTrans();
        $row['update_time'] = date('Y-m-d H:i:s', time());
        $row['add_time'] = date('Y-m-d H:i:s', time());
        $row['is_smallshopsell'] = 1;
        $row['is_copy'] = 2;
        $row['verifyStatus'] = 1;
        $insertId = Db::table('goods_info')->insertGetId($row);
        $saveUniqueId = Db::table('goods_info')->where(['id' => $insertId])->update(['uniqueId' => substr(MD5($insertId), 0, 13)]);
        //复制图片
        $goodsimgList = Db::table('goods_images')->where('goods_id', $goodsId)->field('id', true)->select();
        foreach ($goodsimgList as $k => $v) {
            $goodsimgList[$k]['goods_id'] = $insertId;
        }
        $imgResult = Db::table('goods_images')->insertAll($goodsimgList);
        //复制分类
        $goodsCategoryList = Db::table('goods_info_to_category')->where('goods_id', $goodsId)->field('id', true)->select();
        foreach ($goodsCategoryList as $k => $v) {
            $goodsCategoryList[$k]['goods_id'] = $insertId;
        }
        $categoryResult = Db::table('goods_info_to_category')->insertAll($goodsCategoryList);
        //复制规格
        $goodsinfoDetailList = Db::table('goods_info_detail')->where('goodsId', '=', $goodsId)->field('id', true)->select();
        foreach ($goodsinfoDetailList as $k => $v) {
            $goodsinfoDetailList[$k]['goodsId'] = $insertId;
            $goodsinfoDetailList[$k]['add_time'] = date('Y-m-d H:i:s', time());
            ;
        }

        $goosdInfoDetailResult = Db::table('goods_info_detail')->insertAll($goodsinfoDetailList);

        $goodsResult = Db::table('goods_info')->where('id', '=', $goodsId)
                ->update(['is_copy' => 1]);
        if ($insertId && $saveUniqueId && $imgResult && $categoryResult && $goosdInfoDetailResult && $goodsResult) {
            Db::commit();
            return $this->ajaxReturn(0, '复制成功，注意修改价格和库存和出厂价', null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(3, '复制失败', null);
        }
    }

    /*
     * 商品销量图表
     * author xfwed 
     * date 2020.10.26
     */

    public function goodsSellCount() {
        $list = Db::table('goods_info')
                ->order('sell_count desc')
                ->limit('0,30')
                ->field('id,name,sell_count')
                ->select();

        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 商品置顶
     * author xfwed 
     * date 2020.12.31
     */

    public function goodsTop() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }
        $data = [
            'sort' => time(),
        ];

        Db::table('goods_info')->where('id', $post['goodsId'])->update($data);
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $post['goodsId']);
        return $this->ajaxReturn(0, '置顶成功', null);
    }

    /*
     * 增加商品虚拟销量
     * author xfwed 
     * date 2020.12.31
     */

    public function virtualSellCount() {
        $post = input('param.');
        $rule = [
            'goodsId' => 'require',
            'num' => 'require',
        ];
        $msg = [
            'goodsId.require' => '请选择产品',
            'num.require' => '虚拟销量必须',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($post)) {
            $error = $validate->getError();

            $this->ajaxReturn(1, $error, null);
        }

        $goodsInfo = Db::table('goods_info')
                ->where('id', $post['goodsId'])
                ->field('id,sell_count,virtual_sell_count')
                ->find();
        $trueSellCount = $goodsInfo['sell_count'] - $goodsInfo['virtual_sell_count'];
        $data = [
            'sell_count' => $trueSellCount + $post['num'],
            'virtual_sell_count' => $post['num'],
        ];

        Db::table('goods_info')->where('id', $post['goodsId'])->update($data);
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlGet($ApiPath . 'smallshop/deleteSearchShopGoods?id=' . $post['goodsId']);
        return $this->ajaxReturn(0, '设置成功', null);
    }

    /* 导出商品订单
     * author xfwed
     * date 2021-01-06
     */

    public function goodsOrderListExcel() {
        $status = input('param.status');
        $start_time = input('param.start_time');
        $end_time = input('param.end_time');
        $ord_num = input('ord_num');

        $is_minishop = input('param.is_minishop'); //1是2否 小店订单
        $goodsname = input('param.goodsname');
        $is_big_brand = input('param.is_big_brand'); //1是2否 大牌商品订单

        if ($status && ($status != 5 && $status != 6)) {
            $where['pd.status'] = $status;
            $where['pg.is_refund'] = ['in', '0,3'];
        }
        if ($status == -1) {
            $where['pd.status'] = 0;
            $where['pg.is_refund'] = ['in', '0,3'];
        }

        if ($status == 5) {
            $where['pg.is_refund'] = 1;
        }

        if ($status == 6) {
            $where['pg.is_refund'] = 2;
        }

        if ($ord_num) {
            $where['pd.order_id'] = $ord_num;
        }
        if ($is_minishop == 1) {
            $where['pd.mini_shop_id'] = ['<>', 0];
        } elseif ($is_minishop == 2) {
            $where['pd.mini_shop_id'] = 0;
        }

        if ($goodsname) {
            $where['pg.name'] = ['like', '%' . $goodsname . '%'];
        }

        if ($is_big_brand == 1) {
            $where['pd.activity_big_brand_id'] = ['<>', 0];
        } elseif ($is_big_brand == 2) {
            $where['pd.activity_big_brand_id'] = 0;
        }

        if ($end_time && $start_time) {
            $where['pd.add_time'] = array('between', array($start_time, $end_time));
        } elseif (empty($end_time) && $start_time) {
            $time = strtotime($start_time);
            $time2 = $time + 24 * 60 * 60;
            $time2 = date('Y-m-d H:i:s', $time2);
            $where['pd.add_time'] = array('between', array($time, $time2));
        }
        //$where['m.machine_type'] = 1;
        $where = isset($where) ? $where : [];
        $goodsOrderList = Db::table('pay_order_detail')->alias('pd')
                ->join(['pay_order_goods' => 'pg'], 'pg.pay_order_id = pd.id', 'left')
                ->join('store s', 's.id = pd.store_id', 'left')
                ->join('custom c', 'c.id=pd.ctm_id', 'left')
                ->join(['brand_info' => 'b'], 'b.id = pd.brand_id', 'left')
                //->join(['da_machine_store_relation' => 'm'], 'm.store_id = pd.store_id','right')
                ->where($where)
                ->field('pd.id,pd.order_id,pd.mini_shop_id,pd.activity_big_brand_id,pg.name,pg.goods_icon,pg.is_refund,s.store_name,pd.add_time create_time,c.custom_name,c.custom_phone,pd.pay_money,pd.status,b.name brand_name')
                ->group('pd.id')
                ->order('pd.id desc')
                ->select();

        foreach ($goodsOrderList as $k => $v) {
            $pgISRefund = $v['is_refund'];
            if ($pgISRefund == 1) {
                $goodsOrderList[$k]['status'] = 5;
            }
            if ($pgISRefund == 2) {
                $goodsOrderList[$k]['status'] = 6;
            }
            $tel = Db::connect('mysql://root:eDKmpHzrfkcKrHavT5NLuQ@47.104.18.180:3306/mbcnew#utf8')
                    ->table('brand_info')->alias('b')
                    ->join(['company_info' => 'c'], 'b.companyId = c.id', 'left')
                    ->where('b.name', $v['brand_name'])
                    ->value('c.tel');
            $goodsOrderList[$k]['tel'] = $tel;
            //判断大牌商品的状态
            $status = $v['status'];
            $activity_big_brand_id = $v['activity_big_brand_id'];
            $order_detail_id = $v['id'];
            if ($status == 1 && $activity_big_brand_id != 0) {
                $advanceRow = Db::table('goods_advance')
                        ->where('order_detail_id', $order_detail_id)
                        ->order('id desc')
                        ->find();
                $type = $advanceRow['type'];
                $status = $advanceRow['status'];
                if ($type == 1) {
                    if ($status != 1) {//没有付定金
                        $goodsOrderList[$k]['status'] = 11; //11待付定金 12等待成团 13待付尾款
                    } else {//付定金了  判断成团没有
                        $groupStatus = Db::table('goods_group_detail')->alias('ggd')
                                ->join([' goods_group' => 'gg'], 'ggd.group_id = gg.id', 'left')
                                ->where('ggd.order_detail_id', $order_detail_id)
                                ->value('gg.status');
                        if ($groupStatus == 1) {
                            $goodsOrderList[$k]['status'] = 12;
                        } else {
                            $goodsOrderList[$k]['status'] = 13;
                        }
                    }
                } elseif ($type == 2) {
                    if ($status != 1) {
                        $goodsOrderList[$k]['status'] = 13;
                    }
                }
            }
        }

        $expTitle = '克克美商品订单';
        $expTableData = $goodsOrderList;

        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle . '(-共计' . count($expTableData) . '条)'); //文件名称
        $fileName = $xlsTitle; //or $xlsTitle 文件名称可根据自己情况设定
        if (empty($expTableData)) {
            $this->error('没有符合条件的订单');
        }
        $ii = 3;
        Vendor('PHPExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[12 - 1] . '1'); //合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle . '  Export time:' . date('Y-m-d H:i:s'));
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(18);
        $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(//居中加粗
                array(
                    'font' => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
        );
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(25); // 第一行的默认高度
        $objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(20); // 所有单元格默认高度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true); //设置宽width
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20); //设置宽width
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //垂直居中
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的  
                    'style' => \PHPExcel_Style_Border::BORDER_THIN, //细边框  
                //'color' => array('argb' => 'FFFF0000'),  
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:M' . (count($expTableData) + 2))->applyFromArray($styleArray); //这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代  


        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', "编号");
        $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', "订单编号");
        $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', "商品名称");
        $objPHPExcel->getActiveSheet()->getStyle('C2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D2', "店铺名称");
        $objPHPExcel->getActiveSheet()->getStyle('D2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E2', "用户名");
        $objPHPExcel->getActiveSheet()->getStyle('E2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F2', "手机号");
        $objPHPExcel->getActiveSheet()->getStyle('F2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G2', "订单金额");
        $objPHPExcel->getActiveSheet()->getStyle('G2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H2', "订单状态");
        $objPHPExcel->getActiveSheet()->getStyle('H2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I2', "是否小店订单");
        $objPHPExcel->getActiveSheet()->getStyle('I2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J2', "是否大牌商品");
        $objPHPExcel->getActiveSheet()->getStyle('J2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K2', "品牌名称");
        $objPHPExcel->getActiveSheet()->getStyle('K2')->applyFromArray(array('font' => array('bold' => true)));
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('L2', "厂家电话");
        $objPHPExcel->getActiveSheet()->getStyle('L2')->applyFromArray(array('font' => array('bold' => true)));
        foreach ($expTableData as $key => $val) {
            $tt = 'A' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['id']); //加  “ ”防止用科学计数法，中间必须有空格，否则无效
            $tt = 'B' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, " " . $val['order_id']);
            $tt = 'C' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['name']);
            $tt = 'D' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['store_name']);
            $tt = 'E' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['custom_name']);
            $tt = 'F' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['custom_phone']);
            $tt = 'G' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['pay_money'] / 100);
            $tt = 'H' . $ii;
            //订单状态,0已取消,1待付款,2待发货,3待收货,4已完成5:已发起退款6已退款11待付定金 12等待成团 13待付尾款
            if ($val['status'] == 0) {
                $orderStatus = '已取消';
            } elseif ($val['status'] == 1) {
                $orderStatus = '待付款';
            } elseif ($val['status'] == 2) {
                $orderStatus = '待发货';
            } elseif ($val['status'] == 3) {
                $orderStatus = '待收货';
            } elseif ($val['status'] == 4) {
                $orderStatus = '已完成';
            } elseif ($val['status'] == 5) {
                $orderStatus = '发起退款';
            } elseif ($val['status'] == 6) {
                $orderStatus = '已退款';
            } elseif ($val['status'] == 11) {
                $orderStatus = '待付定金';
            } elseif ($val['status'] == 12) {
                $orderStatus = '等待成团';
            } elseif ($val['status'] == 13) {
                $orderStatus = '待付尾款';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $orderStatus);
            $tt = 'I' . $ii;
            if ($val['mini_shop_id'] > 0) {
                $mini_shop_id = '是';
            } else {
                $mini_shop_id = '否';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $mini_shop_id);
            $tt = 'J' . $ii;
            if ($val['activity_big_brand_id'] > 0) {
                $bigBrand = '是';
            } else {
                $bigBrand = '否';
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $bigBrand);
            $tt = 'K' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['brand_name']);
            $tt = 'L' . $ii;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($tt, $val['tel']);
            $ii++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Pragma: no-cache");
        header("Expires: 0");
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /* 订单自提 不需要厂家发货
     * author xfwed
     * date 2021-09-15
     */

    public function ownGet() {
        $rule = [
            'id' => 'require|integer',
        ];
        $msg = [
            'id.require' => '订单编号必须',
            'id.integer' => '订单编号为数字',
        ];
        $validate = new Validate($rule, $msg);
        $post = input('param.');
        if (!$validate->check($post)) {
            $error = $validate->getError();
            return $this->ajaxReturn(3, $error, null);
        }
        //有退款就不能再发货了
        $is_refund = Db::table('pay_order_goods')
                ->where('pay_order_id', $post['id'])
                ->value('is_refund');
        if ($is_refund == 1 || $is_refund == 2) {
            return $this->ajaxReturn(3, '该订单已申请退款，不需要发货了', null);
        }

        $data = [
            //'logistics' => $post['logisticsName'],
            'logistics_date' => date('Y-m-d H:i:s'),
            //'logistics_num' => $post['logisticsNum'],
            'status' => 3,
            'freight_type' => 2,
            'send_time' => date('Y-m-d H:i:s'),
        ];

        // 订单数据
        $old_order = Db::table('pay_order_detail')
                ->where('id', $post['id'])
                ->find();
        if (!$old_order) {
            return $this->ajaxReturn(3, '订单无效或已删除', null);
        }

        // 订单不是待发货
        if ($old_order['status']!=2) {
            return $this->ajaxReturn(3, '订单已完成或已失效', null);
        }
        
        $save = Db::table('pay_order_detail')
                ->where('id', $post['id'])
                ->update($data);
        
        $order_id = $old_order['order_id'];
        //调用java接口 确认收货
        $ApiPath = config('appconfig.ApiPath');
        $relust = Utils::curlPost($ApiPath . '/order/updateSubOrderToCompleted?subOrderNo='.$order_id);
        $relust = json_decode($relust,true);
        if($save && $relust['msg']){
            return $this->ajaxReturn(0, '成功', null);
        }  else {
            return $this->ajaxReturn(3, '失败', null);
        }
    }

}
